<template>
  <div class="page-container">
    <!--面包屑导航-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>营销中心</el-breadcrumb-item>
        <el-breadcrumb-item>通用促销</el-breadcrumb-item>
        <el-breadcrumb-item>满量促销</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--工具栏-->
    <div class="toolbar">
      <el-form :inline="true" :model="filters" :size="size" ref="filters">
        <el-row class="search-input">
          <el-form-item prop="promName" label="活动名称：">
            <el-input v-model="filters.promName" placeholder="活动名称" clearable></el-input>
          </el-form-item>
          <el-form-item prop="promotionId" label="活动ID：">
            <el-input v-model="filters.promotionId" placeholder="活动ID" clearable></el-input>
          </el-form-item>
          <el-form-item prop="creator" label="创建人：">
            <el-input v-model="filters.creator" placeholder="创建人" clearable></el-input>
          </el-form-item>
            <el-form-item prop="startTime" label="活动时间：">
              <el-date-picker
                v-model="filters.startTime"
                type="date"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                placeholder="活动开始"
                class="input_postion"
              ></el-date-picker>
            </el-form-item>
            <span class="times-to">-</span>
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="filters.endTime"
                type="date"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                placeholder="活动结束"
                class="input_postion"
              ></el-date-picker>
            </el-form-item>
          </el-row>
        <el-row class="search-button button20">
          <el-form-item>
            <kt-button
              icon="el-icon-search" label="搜索"
              @click="getPromotionList()"
              type="primary"
            />
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-refresh" :label="$t('action.reset')" type="primary" plain @click="resetForm('filters')" />
          </el-form-item>
          <el-form-item>
            <kt-button
              label="创建活动"
              @click="createPage()"
              type="primary"
              perms="market:fullnum:add"
            />
          </el-form-item>
          <el-form-item>
            <kt-button
              label="通过模板添加活动"
              @click="createCouponTemplate()"
              type="primary"
              perms="market:fullnum:temp"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="tab-container">
      <el-tabs v-model="activeName">
        <el-tab-pane
          v-for="item in tabMapOptions"
          :key="item.key"
          :label="item.label"
          :name="item.key"
        ></el-tab-pane>
        <!-- tab表格 -->
        <el-table
          :data="tableData"
          :highlight-current-row="true"
          :max-height="1500"
          size="mini"
          v-loading="loading"
          :align="align"
          border
          style="width: 100%"
        >
          <el-table-column width="300" align="center" prop="promotionId" label="活动ID"></el-table-column>
          <el-table-column width="240" align="center" prop="promName" label="活动名称"></el-table-column>
          <el-table-column width="300" align="center" label="活动时间">
            <template slot-scope="scope">
              <span
                v-if="scope.row.startTime != null && scope.row.endTime != null"
              >{{scope.row.startTime}}至{{scope.row.endTime}}</span>
            </template>
          </el-table-column>
          <el-table-column width="100" align="center" prop="address" label="活动状态">
            <template slot-scope="scope">
              <span v-if="scope.row.status == 9">活动草稿</span>
              <span v-else-if="statusFormat(scope.row) == 11">待提交</span>
              <span v-else-if="statusFormat(scope.row) == 12">待审核</span>
              <span v-else-if="statusFormat(scope.row) == 13">未开始</span>
              <span v-else-if="statusFormat(scope.row) == 14">审核未通过</span>
              <span v-else-if="statusFormat(scope.row) == 15">进行中</span>
              <span v-else-if="statusFormat(scope.row) == 16">已过期</span>
              <span v-else-if="statusFormat(scope.row) == 17">已结束</span>
              <span v-else-if="scope.row.status == 7">已关闭</span>
            </template>
          </el-table-column>
          <el-table-column width="100" align="center" label="活动类型">
            <template slot-scope="scope">
              <span v-if="scope.row.frontPromType == '2001'">减价</span>
              <span v-else-if="scope.row.frontPromType == '2002'">折扣</span>
              <span v-else-if="scope.row.frontPromType == '2003'">减运费</span>
            </template>
          </el-table-column>
          <el-table-column width="240" align="center" prop="creatorName" label="创建人"></el-table-column>
          <el-table-column width="240" align="center" prop="createTime" label="创建时间"></el-table-column>
          <el-table-column width="330" align="left" fixed="right" label="操作">
            <template slot-scope="scope">
              <el-button
                type="text"
                @click="handleClick(scope.row)"
                v-if="scope.row.status != 9"
                size="mini"
                style
              >查看</el-button>
              <kt-button
                type="text"
                size="mini"
                v-if="scope.row.status == 9 || statusFormat(scope.row) == 11 || statusFormat(scope.row) == 14"
                v-show="scope.row.editFlag"
                @click="editInfo(scope.row)"
                perms="market:coupon:edit"
                label="编辑"
              />
              <kt-button
                type="text"
                size="mini"
                v-if="statusFormat(scope.row) == 11 || scope.row.status == 9"
                v-show="scope.row.editFlag"
                @click="deleteInfo(scope.row)"
                perms="market:coupon:delete"
                label="删除"
              />
              <kt-button
                type="text"
                size="mini"
                v-if="scope.row.status != 9"
                @click="copyInfo(scope.row)"
                v-show="scope.row.editFlag"
                perms="market:coupon:copy"
                label="复制"
              />
              <kt-button
                type="text"
                size="mini"
                v-if="statusFormat(scope.row) == 13 || statusFormat(scope.row) == 15"
                v-show="scope.row.editFlag"
                @click="closeInfo(scope.row)"
                perms="market:coupon:colse"
                label="关闭"
              />
            </template>
          </el-table-column>
        </el-table>
        <div class="t_r">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="filters.start"
            :page-sizes="[10, 20, 50, 100 ,300 , 500]"
            :page-size="filters.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-tabs>
    </div>
    <!--弹出框-->
    <el-dialog title="请选择秒杀/拼团/满额促销形式" :visible.sync="flag" class="el-dialog-form">
      <div class="flex mb20">
        <p class="form-left-width">活动类型：</p>
        <el-select v-model="form.region" placeholder="请选择秒杀/拼团/满额促销形式">
          <el-option label="秒杀" value="one"></el-option>
          <el-option label="拼团" value="two"></el-option>
          <el-option label="满额促销" value="three"></el-option>
        </el-select>
      </div>
      <div class="flex mb20">
        <p class="form-left-width">当前参与用户：</p>
        <el-checkbox-group v-model="joinCheck">
          <el-checkbox v-for="item in joinList" :label="item" :key="item" class="mr20"></el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="flex mb20">
        <p class="form-left-width">推送方式：</p>
        <el-checkbox-group v-model="wayCheck">
          <el-checkbox v-for="item in wayList" :label="item" :key="item" class="mr20"></el-checkbox>
        </el-checkbox-group>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" plain @click="flag = false">取消</el-button>
        <el-button type="primary" @click="checked">提交</el-button>
      </span>
    </el-dialog>

    <el-dialog :visible.sync="couponTemplatedialogVisible" title="使用模板">
      <div class="flex">
        <el-form :inline="true" class="demo-form-inline2" size="small" v-model="templateDataForm">
          <el-form-item label="ID：">
            <el-input v-model="templateDataForm.id" placeholder="ID" clearable></el-input>
          </el-form-item>
          <el-form-item label="名称：">
            <el-input v-model="templateDataForm.templateName" placeholder="名称" clearable></el-input>
          </el-form-item>
        </el-form>
        <el-row class="t_r mb30">
          <el-button type="primary" icon="el-icon-search" @click="queryTemplateList">搜索</el-button>
          <!-- <el-button icon="el-icon-refresh-left" @click="restForm('storeDataForm')">清空</el-button> -->
        </el-row>
      </div>
      <div class="table-section">
        <el-table
          :data="templateTableData"
          v-loading="templateLoading"
          :highlight-current-row="true"
          ref="multipleTable"
          border
          :size="size"
        >
          <el-table-column prop="id" label="ID" align="center"></el-table-column>
          <el-table-column align="center" prop="promType" label="活动类型">
            <template>
              <span>满量促销</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="templateName" label="模板名称"></el-table-column>
          <el-table-column align="center" prop="creatorName" label="创建人"></el-table-column>
          <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="260">
            <template slot-scope="scope">
              <el-button @click="used(scope.row)" type="text" class="textButton" size="small">使用</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="t_r" v-if="templateTableData.length > 0">
        <el-pagination
          @size-change="templatehandleSizeChange"
          @current-change="templatehandleCurrentChange"
          :current-page="templateDataForm.start"
          :page-sizes="[10]"
          :page-size="templateDataForm.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="templateListTotal"
        ></el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    front_prom_types,
    chanel_codes,
    prom_types
  } from "@/market/dict/marketDict";
  import KtButton from "@/views/Core/KtButton";
  import { format } from "@/utils/datetime";
  import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
  import { darkmagenta } from "color-name";
  import tabPane from "./components/TabPaneSeckill";
  import { channelCodeConverter } from "@/market/dict/marketDict";

  export default {
    name: "Tab",
    components: {
      tabPane,
      KtButton,
      TableColumnFilterDialog
    },
    data() {
      return {
        pageNumber: 1,
        pageSize: 10,
        total: 0,
        loading: false,
        align: "center",
        tableData: [],
        flag: false,
        form: {
          region: ""
        },
        option1: 1,
        option1: 2,
        option1: 3,
        tabMapOptions: [
          { label: '全部', key: '99' },
          { label: '未开始', key: '3' },
          { label: '待提交', key: '1' },
          { label: '待审核', key: '2' },
          { label: '审核未通过', key: '4' },
          { label: '进行中', key: '5' },
          { label: '已过期', key: '6' },
          { label: '已关闭', key: '7' },
          { label: '已结束', key: '8' },
          { label: '活动草稿', key: '9' },
        ],
        activeName: "99",
        createdTimes: 0,
        size: "small",
        filters: {
          start: 1,
          limit: 10,
          promName: null,
          promotionId: null,
          id: "",
          promType: 2,
          channelCode: "",
          activityType: "",
          merchantId: null,
          creator: "",
          startTime: "",
          endTime: "",
          operatorStoreId: null,
          type: "",
          status: null,
          t: "sysConfig",
          queryname: ""
        },
        frontPromTypes: this.getFrontPromType(),
        promTypes: this.getPromType(),
        channelCodes: chanel_codes,
        activityTypes: [
          { activityType: "", label: "请选择" },
          { activityType: "0", label: "自建" },
          { activityType: "1", label: "报名" }
        ],
        merchantIds: [{ merchantId: null, label: "请选择" }],
        storeIds: [{ storeId: null, label: "请选择" }],
        joinCheck: [],
        joinList: ["已使用用户", "未使用用户"],
        wayCheck: [],
        wayList: ["短信", "小程序", "网站", "H5", "邮件"],
        couponTemplatedialogVisible: false, //活动模板弹窗
        templateDataForm: {
          start: 1,
          limit: 10,
          promType: 2 //满量
        }, //模板搜索条件
        templateTableData: [], //模板List
        templateLoading: false, //模板table加载状态
        templateListTotal: 0, //模板LIst总条数
        tabsIndex: "first"
      };
    },
    methods: {
      /**
       * 状态格式化
       */
      statusFormat(row) {
        if (
          row.status == 1 &&
          new Date().getTime() <= new Date(row.startTime).getTime()
        ) {
          //待提交
          return 11;
        } else if (
          row.status == 2 &&
          new Date().getTime() <= new Date(row.startTime).getTime()
        ) {
          //待审核
          return 12;
        } else if (
          row.status == 11 &&
          new Date().getTime() <= new Date(row.startTime).getTime()
        ) {
          //未开始
          return 13;
        } else if (
          row.status == 4 &&
          new Date().getTime() <= new Date(row.startTime).getTime()
        ) {
          //审核未通过
          return 14;
        } else if (
          row.status == 11 &&
          new Date().getTime() >= new Date(row.startTime).getTime() &&
          new Date().getTime() <= new Date(row.endTime).getTime()
        ) {
          //进行中
          return 15;
        } else if (
          (row.status == 1 || row.status == 2 || row.status == 4) &&
          new Date().getTime() > new Date(row.startTime).getTime()
        ) {
          //已过期
          return 16;
        } else if (
          row.status == 11 &&
          new Date().getTime() > new Date(row.endTime).getTime()
        ) {
          //已结束
          return 17;
        }
      },
      /**
       * 根据活动模板创建优惠券
       */
      createCouponTemplate() {
        this.couponTemplatedialogVisible = true;
        this.tempPageQuery();
      },
      /**
       * 使用模板
       */
      used(row) {
        const loading = this.$loading({
          lock: true,
          text: "小的正在加载中,请稍后...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        this.utils.request.fullNumCopyConfig(
          { promotionId: row.promotionId },
          res => {
            loading.close();
            if (res.code == "0000") {
              this.couponTemplatedialogVisible = false;
              this.$router.push({
                path: "/FullNumPromotionAdd",
                query: { promotionId: res.data }
              });
            } else {
              this.$message({ message: res.msg, type: "error" });
            }
          }
        );
      },
      /**
       * 搜索模板
       */
      queryTemplateList() {
        this.$set(this.templateDataForm, "start", 1);
        this.tempPageQuery();
      },
      /**
       * 分页数据切换
       */
      templatehandleSizeChange() {},
      /**
       * 页码切换
       */
      templatehandleCurrentChange() {
        this.tempPageQuery();
      },
      /**
       * 查询模板数据
       */
      // 分页查询
      tempPageQuery() {
        this.templateLoading = true;
        let callback = res => {
          this.templateLoading = false;
          if (res.code == "0000") {
            this.templateTableData = res.data.rows;
            this.templateListTotal = res.data.total;
          } else {
            this.$message({ message: "查询失败", type: "fail" });
          }
        };
        this.utils.request.templatePageQuery(this.templateDataForm, callback);
      },
      /**
       * 编辑
       */
      editInfo(row) {
        this.$router.push({
          path: "/FullNumPromotionAdd",
          query: { promotionId: row.promotionId }
        });
      },
      /**
       * 删除
       */
      deleteInfo(row) {
        let that = this;
        this.$confirm("确定要执行删除操作么？删除后不可恢复!", "提示", {
          type: "warning"
        })
          .then(() => {
            this.utils.request.fullNumDeleteConfig(
              { promotionId: row.promotionId },
              res => {
                that.$message({ message: "删除成功", type: "success" });
                that.findPage();
              }
            );
          })
          .catch(() => {});
      },
      /**
       * 复制
       */
      copyInfo(row) {
        let that = this;
        this.$confirm("确定要复制该活动？", "提示", {
          type: "warning"
        })
          .then(() => {
            this.utils.request.fullNumCopyConfig(
              { promotionId: row.promotionId },
              res => {
                that.$message({ message: "复制成功", type: "success" });
                that.findPage();
              }
            );
          })
          .catch(() => {});
      },
      /**
       * 关闭
       */
      closeInfo(row) {
        let that = this;
        let flag = "正在进行中";
        if (row.status == "3") {
          flag = "即将进行";
        }
        this.$confirm(
          "该活动" + flag + "，确定要关闭它？关闭后不可再次开启。",
          "提示",
          {
            type: "warning"
          }
        )
          .then(() => {
            this.utils.request.fullNumCloseConfig(
              { promotionId: row.promotionId },
              res => {
                that.$message({ message: "关闭成功", type: "success" });
                that.findPage();
              }
            );
          })
          .catch(() => {});
      },
      handleClick(row) {
        this.$router.push({
          path: "/FullNumDetail",
          query: { promotionId: row.promotionId }
        });
      },
      handleSizeChange(val) {
        this.$set(this.filters, "limit", val);
        this.findPage();
      },
      handleCurrentChange(val) {
        this.$set(this.filters, "start", val);
        this.findPage();
      },
      findPage() {
        let that = this;
        this.loading = true;
        // this.filters.pageNo = this.pageNumber;
        // this.filters.pageSize = this.pageSize;
        this.filters.merchantId =
          this.filters.merchantId == "" ? null : this.filters.merchantId;
        this.filters.operatorStoreId =
          this.filters.operatorStoreId == ""
            ? null
            : this.filters.operatorStoreId;

        this.filters.status =
          this.filters.status == "99" ? null : this.filters.status;
        this.utils.request.fullNumQueryConfigPage(this.filters, res => {
          that.loading = false;
          that.tableData = res.data.rows;
          that.total = res.data.total;
        });
      },

      genChannelCode: function(code) {
        return channelCodeConverter(code);
      },
      // 时间格式化
      dateFormat: function(row, column, cellValue, index) {
        return format(row[column.property]);
      },

      resetForm(formName) {
        if (this.$refs[formName] != undefined) {
          this.$refs[formName].resetFields();
        }
        this.$set(this.filters, "start", 1);
        this.$set(this.filters, "limit", 10);
        this.findPage();
      },
      createPage() {
        this.$router.push("/FullNumPromotionAdd");
        // this.$router.push("/CreatePromotion"+"?auth=1");
      },
      getPromotionList() {
        if (
          this.filters.startTime != "" &&
          this.filters.endTime != "" &&
          this.filters.startTime != null &&
          this.filters.endTime != null
        ) {
          if (
            new Date(this.filters.startTime) >= new Date(this.filters.endTime)
          ) {
            this.$message({
              message: "开始时间不能大于等于结束时间",
              type: "error"
            });
            return false;
          }
        }
        this.$set(this.filters, "start", 1);
        this.$set(this.filters, "limit", 10);
        this.findPage();
        // this.$refs.child[0].listQuery.pageNo = 1;
        // this.$refs.child[0].getList();
      },
      changeMerchant() {
        let this_ = this;
        this.utils.request.queryStoreList(
          { start: 1, limit: 10000000, merchantId: this.filters.merchantId },
          function(res) {
            if (res.code == "0000") {
              res.data.rows.forEach(item => {
                //,{'storeId':'0','label':'张小二bbc店铺'},{'storeId':'1','label':'张小二的京东店'}
                let store = {};
                store.storeId = item.id;
                store.label = item.storeName;
                this_.storeIds.push(store);
              });
            }
          }
        );
      },
      getFrontPromType: function(row, column, cellValue, index) {
        return front_prom_types.filter(e => {
          return e.code == "skill_front_prom_type";
        });
      },

      getPromType: function(row, column, cellValue, index) {
        return prom_types.filter(e => {
          return e.code == "skill_promotion";
        });
      },
      checked() {
        this.flag = false;
        if (this.form.region == "one") {
          this.$router.push("/SeckillPromotionEvent" + "?auth=0");
        } else if (this.form.region == "two") {
          this.$router.push("/GroupActivityComponents?auth=0");
        } else {
          this.$router.push("/CreatePromotion3");
        }
      },
      SecondSell() {
        this.flag = true;
      }
    },
    watch: {
      activeName(val) {
        // this.$router.push(`${this.$route.path}?tab=${val}`);
        this.filters.status = val == "0" ? "" : val;
        this.$set(this.filters, "start", 1);
        this.$set(this.filters, "limit", 10);
        this.findPage();
      }
    },
    created() {
      //获取商家列表
      let this_ = this;
      this.utils.request.queryMerchantList(
        { start: 1, limit: 10000000 },
        function(res) {
          if (res.code == "0000") {
            res.data.rows.forEach(item => {
              let merchant = {};
              merchant.merchantId = item.id;
              merchant.label = item.name;
              this_.merchantIds.push(merchant);
            });
          }
        }
      );
      this.changeMerchant();
      // init the default selected tab
      //this.frontPromTypes = front_prom_types;
      const tab = this.$route.query.tab;
      if (tab) {
        this.activeName = tab;
      }
    },
    mounted() {
      //查询列表
      this.findPage();
    }
  };
</script>

<style scoped lang="scss">
  @import '../../../assets/css/public.scss';
         .search-button{
  margin: 0px 0px 20px;
  padding-bottom: 0px;
}
.t_r{
  margin-top: 0px !important;
  margin-bottom: 30px;
}
</style>
